package net.baribeau.pdfgen;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Source;
import javax.xml.transform.dom.DOMSource;

/**
 * Static methods for XML generation
 */
public class XmlBuilderUtil {

    private static final DocumentBuilderFactory DOC_FACTORY = DocumentBuilderFactory.newInstance();

    private XmlBuilderUtil() {
        // only static, no instances
    }

    /**
     * Creates a new and empty XML document
     *
     * @return A newly created empty XML document
     * @throws ParserConfigurationException 
     * if a ParserConfigurationException is encountered while creating the document
     */
    public static Document createDocument() throws ParserConfigurationException {
        
            return DOC_FACTORY.newDocumentBuilder().newDocument();
        
    }

    /**
     * Creates and adds a new element to the specified parent element
     *
     * @param parent The parent element
     * @param name   The name for the new element
     * @return The new element (after adding it to the parent)
     */
    public static Element addElement(Element parent, String name) {
        final Element element = parent.getOwnerDocument().createElement(name);
        parent.appendChild(element);
        return element;
    }

    
    /**
     * Creates and adds a new element with the specified value to the given document
     *
     * @param parent The parent element
     * @param name   The name for the new element
     * @param value  The new elements value (null is converted to the empty string)
     */
    public static void addElement(Element parent, String name, Object value) {
        final Document document = parent.getOwnerDocument();
        final Element child = document.createElement(name);
        parent.appendChild(child);

        final String valueText;
        if (value == null) {
            valueText = "";
        } else {
            valueText = value.toString();
        }

        child.appendChild(document.createTextNode(valueText));
    }

    /**
     * Returns an XML Source object representing the specified document (and all its nodes)
     *
     * @param document An XML document
     * @return A normalized XML Source representing the document
     */
    public static Source getSource(Document document) {
        document.getDocumentElement().normalize();
        return new DOMSource(document);
    }
    
    
}//XmlBuildUtil
